package com.module.antiFake.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;

import base.common.CUDEnum;
import base.dao.GenericHibernateDao;
import base.util.Page;
import base.util.SQLUtil;

import com.module.antiFake.vo.AntiFakeScanHistory;

public class AntiFakeScanHistoryDao extends GenericHibernateDao<AntiFakeScanHistory, Long>{
	private static AntiFakeScanHistoryDao antiFakeScanHistoryDao;
	//扫码历史记录操作类;
	private static AntiFakeScanTimesDao antiFakeScanTimesDao = AntiFakeScanTimesDao.getInstance();
	
	private final static String SECOND_SCANED = "1";
	
	/**
	 * 获取扫码记录单例;
	 * @return
	 */
	public synchronized static AntiFakeScanHistoryDao getInstance() {
		if(antiFakeScanHistoryDao == null){
			antiFakeScanHistoryDao = new AntiFakeScanHistoryDao();
		}
		return antiFakeScanHistoryDao;
	}
	
	/**
	 * 保存扫码信息;
	 * @return 
	 */
	public boolean save(Session session,AntiFakeScanHistory antiFakeScanHistory){
		boolean flag = false;
		antiFakeScanHistory.setStatus(CUDEnum.C.toString());
        session.save(antiFakeScanHistory);
        //通过扫码记录更新扫码记录统计表;
        flag = antiFakeScanTimesDao.saveOrUpdateForHistory(session,antiFakeScanHistory);
        setScanCheckedDate(session,antiFakeScanHistory);
        return flag;
	}

	/**
	 * 如果码被击穿，则把击穿时间传给手机;
	 * @param session
	 * @param antiFakeScanHistory
	 */
	private void setScanCheckedDate(Session session,
			AntiFakeScanHistory history) {
		Date result = null;
		if(history.getLayerNum()==1 &&  history.getSecondScaned().equals(new Short(SECOND_SCANED))){
			AntiFakeScanHistory antiFakeScanHistory = findUniqueObjectBySQL(session,"FROM AntiFakeScanHistory antiFakeScanHistory " +
					"WHERE antiFakeScanHistory.id = (SELECT min(history.id) FROM AntiFakeScanHistory history WHERE history.firstCodeInfo='"+
					history.getCodeInfo()+"'  AND "+SQLUtil.getExistWhere("history")+")");
			if(antiFakeScanHistory!=null){
				result = antiFakeScanHistory.getCreatetime();
				history.setAntiFakeScanDate(result);
			}
		}
	}

	/**
	 * 读取当前码上一次扫码时间
	 * @param codeInfo
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Date getLastScanDateFromCode(Session session,AntiFakeScanHistory history) {
		Date result = null;
		String hql = "select antiFakeScanHistory.createtime FROM AntiFakeScanHistory antiFakeScanHistory " +
				"WHERE antiFakeScanHistory.id = (SELECT max(history.id) FROM AntiFakeScanHistory history WHERE history.codeInfo= ? " +
				" AND history.id!= ?  AND "+SQLUtil.getExistWhere("history")+")";
		Query query = session.createQuery(hql);
		query.setParameter(0, history.getCodeInfo()).setParameter(1, history.getId());
		List<Date> list = query.list();
		if(list != null && !list.isEmpty())
			result = list.get(0);
		return result;
	}
	
	/**
	 * 读取当前码第一次扫码时间
	 * @param codeInfo
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Date getFirstScanDateFromCode(Session session,AntiFakeScanHistory history) {
		Date result = null;
		String hql = "select antiFakeScanHistory.createtime FROM AntiFakeScanHistory antiFakeScanHistory " +
				"WHERE antiFakeScanHistory.id = (SELECT min(history.id) FROM AntiFakeScanHistory history WHERE history.codeInfo=? " +
				"AND history.id!=? AND "+SQLUtil.getExistWhere("history")+")";
		Query query = session.createQuery(hql);
		query.setParameter(0, history.getCodeInfo()).setParameter(1, history.getId());
		List<Date> list = query.list();
		if(list != null && !list.isEmpty())
			result = list.get(0);
		return result;
	}

	/**
	 * 通过网页查询条件，列出扫码记录
	 * @param antiFakeScanHistory
	 * @param page
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Page getList(Session session,
		AntiFakeScanHistory antiFakeScanHistory, Page page) {
		String whereStr = "";
		StringBuffer hql = new StringBuffer("select history,");
		hql.append(" (select aflbs.county from AntiFakeLBS aflbs where aflbs.id = history.lbsId) as location");
		hql.append(" FROM AntiFakeScanHistory history WHERE history.status !='D' ");
		String hqlCount = "SELECT count(*) FROM AntiFakeScanHistory history  WHERE history.status !='D'";
		if(StringUtils.isNotBlank(antiFakeScanHistory.getImei())){
			whereStr += " AND history.imei='"+antiFakeScanHistory.getImei()+"' ";
		}
		if(StringUtils.isNotBlank(antiFakeScanHistory.getCodeInfo())){
			whereStr += " AND history.codeInfo='"+antiFakeScanHistory.getCodeInfo()+"' ";
		}
		if(StringUtils.isNotBlank(antiFakeScanHistory.getOrgid())){
			whereStr += " AND history.orgid='"+antiFakeScanHistory.getOrgid()+"' ";
		}
		Query query = session.createQuery(hql.append(whereStr).append(" ORDER BY history.createtime DESC").toString());
        query.setFirstResult(page.getStart()).setMaxResults(page.getLimit()); 
        page.setTotal((long) ((Long) session.createQuery(hqlCount+whereStr)
          .uniqueResult()).intValue());
        final List voList = new ArrayList<AntiFakeScanHistory>();
		CollectionUtils.transform(query.list(), new Transformer() {
			@Override
			public Object transform(Object obj) {
				AntiFakeScanHistory vo = new AntiFakeScanHistory();
				Object row[] = (Object[]) obj;
				try {
					BeanUtils.copyProperties(vo, (AntiFakeScanHistory) row[0]);
				} catch (Exception e) {
					e.printStackTrace();
				}
				vo.setLocation((String) row[1]);
				voList.add(vo);
				return vo;
			}
		});
        page.setRows(voList);	
		return page;
	}

	/**
	 * 统计相应批次销售区域与扫码区域的不一致
	 * @param session 
	 * @param batchNo
	 * @return
	 */
	public Long countByBatchNo(Session session, String batchNo) {
		String hql = "SELECT count(*) FROM AntiFakeScanHistory history where (history.lbsId!=0 and history.lbsId!=null " +
				"and history.salesAreaId!=0 and history.salesAreaId!=null) and history.salesAreaId!=history.lbsId" +
				" and history.batchNo='"+batchNo+"'";
		return (Long) session.createQuery(hql).uniqueResult();
	}
	
}
